<script setup>
import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import {
    Back,
    VideoPlay,
    VideoPause,
    RefreshRight,
    AlarmClock,
    Loading,
    Star,
    Delete,
    View
} from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const loading = ref(true)
const iframeLoaded = ref(false)
const showError = ref(false)

// DIFY API相关状态
const apiKey = ref('') // DIFY API密钥，应从环境变量或配置中获取
const conversationId = ref('') // 当前会话ID
const messages = ref([]) // 会话消息列表
const showCollections = ref(false) // 是否显示收藏列表
const collectionsLoading = ref(false) // 收藏列表加载状态
const collections = ref([]) // 收藏的对话列表

// 番茄钟相关状态
const pomodoroVisible = ref(false)
const pomodoroTime = ref(25)
const breakTime = ref(5)
const isTimerRunning = ref(false)
const currentTime = ref(0)
const timerType = ref('pomodoro') // pomodoro 或 break
const timerInterval = ref(null)
const completedPomodoros = ref(0)

// 计算剩余时间的格式化显示
const formattedTime = computed(() => {
    const minutes = Math.floor(currentTime.value / 60)
    const seconds = currentTime.value % 60
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})

// 初始化DIFY API
const initDifyAPI = () => {
    // 从环境变量或配置中获取API密钥
    apiKey.value = 'your_dify_api_key' // 实际应用中应使用环境变量

    // 设置axios默认请求头
    axios.defaults.headers.common['Authorization'] = `Bearer ${apiKey.value}`
}

// 监听iframe消息，获取conversationId
const setupMessageListener = () => {
    window.addEventListener('message', (event) => {
        // 只处理来自DIFY的消息
        if (event.origin === 'http://121.40.242.43') {
            try {
                const data = JSON.parse(event.data)
                if (data.type === 'conversation_created' && data.conversation_id) {
                    conversationId.value = data.conversation_id
                    fetchMessages()
                }
            } catch (error) {
                console.error('处理iframe消息失败', error)
            }
        }
    })
}

// 获取当前会话的消息
const fetchMessages = async () => {
    if (!conversationId.value) return

    try {
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        const username = studentInfo.username || studentInfo.stu_id

        const response = await axios.get('http://121.40.242.43/v1/messages', {
            params: {
                conversation_id: conversationId.value,
                user: username,
                limit: 50
            }
        })

        messages.value = response.data?.data || []
    } catch (error) {
        console.error('获取对话消息失败:', error)
    }
}

// 收藏消息
const collectMessage = async (message) => {
    try {
        // 临时收藏功能
        if (message.id === 'temp') {
            // 如果没有实际消息，则显示一个提示
            ElMessage.info('请先与AI助手进行对话后再收藏')
            return
        }

        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        const username = studentInfo.username || studentInfo.stu_id

        // 1. 给DIFY消息点赞
        await axios.post(`http://121.40.242.43/v1/messages/${message.id}/feedbacks`, {
            rating: 'like',
            user: username
        })

        // 2. 将消息保存到本地存储（由于后端API可能尚未实现）
        const savedCollections = JSON.parse(localStorage.getItem('aiChatCollections') || '[]')
        const newCollection = {
            id: Date.now(),
            message_id: message.id,
            conversation_id: message.conversation_id,
            query: message.query || '对话问题',
            answer: message.answer || '助手回答',
            collected_at: new Date().toISOString()
        }

        savedCollections.push(newCollection)
        localStorage.setItem('aiChatCollections', JSON.stringify(savedCollections))

        ElMessage.success('对话已收藏')
        fetchCollections()
    } catch (error) {
        console.error('收藏对话失败:', error)
        ElMessage.error('收藏对话失败，请稍后重试')
    }
}

// 获取收藏的对话
const fetchCollections = async () => {
    collectionsLoading.value = true
    try {
        // 从localStorage获取收藏的对话
        const savedCollections = JSON.parse(localStorage.getItem('aiChatCollections') || '[]')
        collections.value = savedCollections

        if (collections.value.length === 0) {
            // 使用测试数据
            collections.value = [
                {
                    id: 1,
                    message_id: 'msg1',
                    conversation_id: 'conv1',
                    query: '什么是二分查找算法？',
                    answer: '二分查找是一种在有序数组中查找特定元素的算法。搜索过程从数组的中间元素开始，如果中间元素正好是目标值，则搜索结束；如果目标值小于中间元素，则在中间元素的左侧继续搜索；如果目标值大于中间元素，则在中间元素的右侧继续搜索。时间复杂度为O(log n)。',
                    collected_at: '2023-05-20T15:35:00Z'
                },
                {
                    id: 2,
                    message_id: 'msg2',
                    conversation_id: 'conv1',
                    query: '解释一下快速排序的原理',
                    answer: '快速排序是一种分治算法，基本思想是：选择一个基准元素，将数组分为两部分，一部分所有元素都小于基准元素，另一部分所有元素都大于基准元素，然后递归地对这两部分进行排序。平均时间复杂度是O(n log n)，最坏情况是O(n²)。',
                    collected_at: '2023-05-22T10:15:00Z'
                }
            ]
            // 保存示例数据到localStorage
            localStorage.setItem('aiChatCollections', JSON.stringify(collections.value))
        }
    } catch (error) {
        console.error('获取收藏对话失败:', error)
        ElMessage.error('获取收藏对话失败，请稍后重试')
    } finally {
        collectionsLoading.value = false
    }
}

// 查看收藏的对话详情
const viewCollectionDetail = (collection) => {
    ElMessageBox.alert(
        `<strong>问题:</strong> ${collection.query}<br><br><strong>回答:</strong> ${collection.answer}`,
        '收藏详情',
        {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            callback: () => {}
        }
    )
}

// 删除收藏
const deleteCollection = async (collection) => {
    try {
        await ElMessageBox.confirm('确定要删除这条收藏的对话吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 从localStorage中删除收藏
        const savedCollections = JSON.parse(localStorage.getItem('aiChatCollections') || '[]')
        const updatedCollections = savedCollections.filter(item => item.id !== collection.id)
        localStorage.setItem('aiChatCollections', JSON.stringify(updatedCollections))

        ElMessage.success('收藏已删除')
        fetchCollections()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除收藏失败:', error)
            ElMessage.error('删除收藏失败，请稍后重试')
        }
    }
}

// 刷新当前对话
const refreshConversation = () => {
    const iframe = document.querySelector('iframe')
    if (iframe) {
        iframe.src = iframe.src
        loading.value = true
        iframeLoaded.value = false
        showError.value = false
        conversationId.value = ''
        messages.value = []
    }
}

// 启动番茄钟
const startTimer = () => {
    if (isTimerRunning.value) return

    // 设置初始时间
    if (currentTime.value <= 0) {
        currentTime.value = timerType.value === 'pomodoro' ? pomodoroTime.value * 60 : breakTime.value * 60
    }
    isTimerRunning.value = true

    // 创建计时器
    timerInterval.value = setInterval(() => {
        if (currentTime.value <= 0) {
            completeTimer()
            return
        }
        currentTime.value--
    }, 1000)
}

// 暂停番茄钟
const pauseTimer = () => {
    if (!isTimerRunning.value) return
    clearInterval(timerInterval.value)
    isTimerRunning.value = false
}

// 重置番茄钟
const resetTimer = () => {
    pauseTimer()
    currentTime.value = timerType.value === 'pomodoro' ? pomodoroTime.value * 60 : breakTime.value * 60
}

// 完成一个计时周期
const completeTimer = () => {
    pauseTimer()

    if (timerType.value === 'pomodoro') {
        completedPomodoros.value++
        ElMessage.success('专注时间结束！休息一下吧')
        timerType.value = 'break'
    } else {
        ElMessage.success('休息结束！继续专注吧')
        timerType.value = 'pomodoro'
    }

    // 播放提示音
    try {
        const audio = new Audio('https://actions.google.com/sounds/v1/alarms/beep_short.ogg')
        audio.play().catch(e => console.error('音频播放失败', e))
    } catch (error) {
        console.error('音频初始化失败', error)
    }

    // 自动开始下一个计时周期
    startTimer()
}

// 关闭番茄钟设置弹窗时启动计时
const handlePomodoroClose = () => {
    pomodoroVisible.value = false
}

// 返回首页
const backToHome = () => {
    router.push('/student/Homepage/PersonalHomepage')
}

// iframe加载完成
const handleIframeLoad = () => {
    loading.value = false
    iframeLoaded.value = true
}

// iframe加载失败
const handleIframeError = () => {
    loading.value = false
    showError.value = true
    ElMessage.error('学习助手加载失败，请稍后再试')
}

// 组件卸载时清除计时器
onUnmounted(() => {
    if (timerInterval.value) {
        clearInterval(timerInterval.value)
    }

    // 移除消息监听器
    window.removeEventListener('message', setupMessageListener)
})

onMounted(() => {
    // 模拟加载过程，3秒后如果iframe还没加载完成，显示超时提示
    setTimeout(() => {
        if (loading.value) {
            ElMessage.warning('加载时间较长，请耐心等待...')
        }
    }, 3000)

    // 初始化番茄钟时间
    currentTime.value = pomodoroTime.value * 60

    // 初始化DIFY API
    initDifyAPI()

    // 设置iframe消息监听
    setupMessageListener()
})

// 监听iframe加载状态，加载完成后获取会话ID和消息
watch(iframeLoaded, (newVal) => {
    if (newVal) {
        // 延迟一段时间等待iframe内部初始化完成
        setTimeout(() => {
            fetchMessages()
        }, 1000)
    }
})
</script>

<template>
    <div class="study-container">
        <!-- 头部区域 -->
        <div class="study-header">
            <div class="header-left">
                <el-button @click="backToHome" type="primary" plain>
                    <el-icon><Back /></el-icon>
                    返回首页
                </el-button>
            </div>
            <div class="header-title">
                <h1>AI学习助手</h1>
            </div>
            <div class="header-right">
                <el-button-group>
                    <el-button type="success" @click="showCollections = true" plain size="small">
                        <el-icon><Star /></el-icon>
                        我的收藏
                    </el-button>
                    <el-button type="warning" @click="refreshConversation" plain size="small">
                        <el-icon><RefreshRight /></el-icon>
                        新对话
                    </el-button>
                </el-button-group>
                <el-tag type="success" v-if="iframeLoaded">在线</el-tag>
                <el-tag type="warning" v-else-if="loading">连接中</el-tag>
                <el-tag type="danger" v-else>离线</el-tag>
            </div>
        </div>

        <!-- 描述区域 -->
        <div class="study-description">
            <el-alert
                title="学习助手使用说明"
                type="info"
                description="这是一个智能学习助手，可以回答您关于课程的任何问题。您可以询问课程内容、请求解释复杂概念，或者获取学习建议。点击右侧星标按钮可以收藏有价值的对话。"
                show-icon
                :closable="false"
            />
        </div>

        <!-- 内容区域 -->
        <div class="iframe-container">
            <div v-if="loading" class="loading-overlay">
                <div class="loading-center">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                    <div class="loading-text">AI学习助手加载中，请稍候...</div>
                </div>
            </div>

            <div v-if="showError" class="error-container">
                <el-empty
                    description="无法连接到学习助手"
                    :image-size="200"
                >
                    <el-button type="primary" @click="window.location.reload()">重新尝试</el-button>
                </el-empty>
            </div>

            <iframe
                v-show="!showError"
                src="http://121.40.242.43/chatbot/c7ZSvPxvxyO1fuIo"
                style="width: 100%; height: 100%;"
                frameborder="0"
                allow="microphone"
                @load="handleIframeLoad"
                @error="handleIframeError"
            ></iframe>

            <!-- 收藏按钮 -->
            <div class="collect-btn">
                <el-tooltip content="收藏当前对话" placement="right" effect="dark">
                    <el-button
                        type="warning"
                        circle
                        size="large"
                        @click="collectMessage(messages.length > 0 ? messages[messages.length - 1] : {id: 'temp', conversation_id: conversationId.value, query: '当前对话', answer: ''})"
                        :disabled="!iframeLoaded"
                    >
                        <el-icon><Star /></el-icon>
                    </el-button>
                </el-tooltip>
            </div>

            <!-- 番茄钟浮动按钮 -->
            <div class="pomodoro-floating-btn" @click="pomodoroVisible = true">
                <div class="timer-display" v-if="isTimerRunning">{{ formattedTime }}</div>
                <el-tooltip content="番茄钟" placement="left" effect="dark">
                    <el-button type="danger" circle>
                        <el-icon class="pomodoro-icon-large"><AlarmClock /></el-icon>
                    </el-button>
                </el-tooltip>
            </div>
        </div>

        <!-- 番茄钟设置对话框 -->
        <el-dialog
            title="番茄钟设置"
            v-model="pomodoroVisible"
            width="300px"
            @close="handlePomodoroClose"
            destroy-on-close
        >
            <div class="pomodoro-container">
                <div class="timer-display-large">
                    {{ formattedTime }}
                </div>

                <div class="timer-status">
                    {{ timerType === 'pomodoro' ? '专注时间' : '休息时间' }}
                </div>

                <div class="timer-controls">
                    <el-button-group>
                        <el-button type="primary" @click="startTimer" :disabled="isTimerRunning">
                            <el-icon><VideoPlay /></el-icon> 开始
                        </el-button>
                        <el-button type="warning" @click="pauseTimer" :disabled="!isTimerRunning">
                            <el-icon><VideoPause /></el-icon> 暂停
                        </el-button>
                        <el-button type="info" @click="resetTimer">
                            <el-icon><RefreshRight /></el-icon> 重置
                        </el-button>
                    </el-button-group>
                </div>

                <el-divider></el-divider>

                <div class="timer-settings">
                    <div class="settings-row">
                        <span>专注时长 (分钟)：</span>
                        <el-input-number
                            v-model="pomodoroTime"
                            :min="1"
                            :max="60"
                            size="small"
                            :disabled="isTimerRunning"
                        />
                    </div>

                    <div class="settings-row">
                        <span>休息时长 (分钟)：</span>
                        <el-input-number
                            v-model="breakTime"
                            :min="1"
                            :max="30"
                            size="small"
                            :disabled="isTimerRunning"
                        />
                    </div>
                </div>

                <div class="completed-stats">
                    <el-tag>已完成 {{ completedPomodoros }} 个番茄</el-tag>
                </div>
            </div>
        </el-dialog>

        <!-- 收藏对话列表弹窗 -->
        <el-dialog
            title="我的收藏"
            v-model="showCollections"
            width="70%"
            destroy-on-close
        >
            <div v-loading="collectionsLoading">
                <div v-if="collections.length === 0" class="empty-collections">
                    <el-empty description="暂无收藏的对话" />
                </div>
                <el-table v-else :data="collections" style="width: 100%">
                    <el-table-column prop="query" label="问题" min-width="200" show-overflow-tooltip />
                    <el-table-column prop="answer" label="回答" min-width="300" show-overflow-tooltip />
                    <el-table-column prop="collected_at" label="收藏时间" width="180">
                        <template #default="scope">
                            {{ new Date(scope.row.collected_at).toLocaleString() }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150">
                        <template #default="scope">
                            <el-button-group>
                                <el-button type="primary" @click="viewCollectionDetail(scope.row)" size="small">
                                    <el-icon><View /></el-icon>
                                </el-button>
                                <el-button type="danger" @click="deleteCollection(scope.row)" size="small">
                                    <el-icon><Delete /></el-icon>
                                </el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>
    </div>
</template>

<style scoped>
.study-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    overflow: hidden;
}

.study-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    height: 50px;
}

.header-title h1 {
    margin: 0;
    font-size: 20px;
    color: #409EFF;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 10px;
}

.study-description {
    margin-bottom: 20px;
}

.iframe-container {
    position: relative;
    flex: 1;
    height: calc(100vh - 70px);
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    background-color: #fff;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 10;
}

.loading-center {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.loading-icon {
    font-size: 40px;
    color: #409EFF;
    animation: rotate 2s linear infinite;
}

@keyframes rotate {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

.loading-text {
    margin-top: 20px;
    color: #606266;
    font-size: 16px;
}

.error-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    width: 100%;
}

.study-footer {
    margin-top: 20px;
    text-align: center;
    color: #909399;
    font-size: 12px;
}

/* 收藏按钮样式 */
.collect-btn {
    position: absolute;
    left: 20px;
    top: 80px;
    z-index: 999;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}

/* 番茄钟样式 */
.pomodoro-floating-btn {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 100;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    padding: 5px;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.4);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(220, 53, 69, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(220, 53, 69, 0);
    }
}

.timer-display {
    background-color: rgba(255, 255, 255, 0.9);
    padding: 2px 8px;
    border-radius: 12px;
    margin-bottom: 5px;
    font-weight: bold;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pomodoro-container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.timer-display-large {
    font-size: 48px;
    font-weight: bold;
    color: #409EFF;
    margin: 10px 0;
}

.timer-status {
    font-size: 16px;
    margin-bottom: 20px;
    color: #606266;
}

.timer-controls {
    margin-bottom: 20px;
}

.settings-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    width: 100%;
}

.completed-stats {
    margin-top: 15px;
}

/* 收藏对话样式 */
.empty-collections {
    padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .study-container {
        padding: 5px;
    }

    .study-header {
        margin-bottom: 5px;
        height: 40px;
    }

    .header-title h1 {
        font-size: 18px;
    }

    .iframe-container {
        height: calc(100vh - 55px);
    }

    .pomodoro-floating-btn {
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        padding: 3px;
    }

    .timer-display-large {
        font-size: 36px;
    }
}

.pomodoro-icon-large {
    font-size: 36px;
    /* 可根据需要调整大小 */
}
</style>
